<template>
    <div class="favorite-jobs-page">
        <div class="top-section">
            <h1>{{$route.meta.title}}</h1>
            <p class="num">共<span>{{queryData.total}}</span>个职位</p>
        </div>
        <el-empty v-if="queryData.total == 0 && !tableLoading" description="暂无收藏职位" />
        <ul class="job-list" v-loading="tableLoading">
            <li v-for="job in tableData" :key="job.id">
                <div class="top">
                <p class="tit">{{ job.name }}</p>
                <span class="period">报名时间：{{ dayjs(job.startTime).format('YYYY-MM-DD') }} - {{ dayjs(job.deadline).format('YYYY-MM-DD') }}</span>
                </div>
                <div class="requirements">
                    <div class="requirement-item">
                        <el-icon><School /></el-icon>
                        {{ getDegreeLabel(job.degree) || '学历不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><Timer /></el-icon>
                        {{ getExperienceLabel(job.workExperience) || '经验不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><Collection /></el-icon>
                        {{ job.major || '专业不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><Location /></el-icon>
                        {{ job.address || '地点未设置' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><User /></el-icon>
                        {{ job.age || '年龄不限' }}
                    </div>
                </div>
                <div class="bottom">
                <div class="job-tags">
                    <el-tag type="info" v-for="tag in job.customizationList" :key="tag">{{ tag }}</el-tag>
                </div>
                <div class="btns">
                    <el-button type="primary" @click="handleJobClick(job.id)">查看详情</el-button>
                    <el-button type="primary" :icon="StarFilled" plain @click="toggleFavorite(job)">取消收藏</el-button>
                    <el-popover placement="right" :width="200" trigger="click" @show="generateQRCode(job.id)" @click.stop>
                        <template #reference>
                        <el-button :icon="Share" @click.stop>分享</el-button>
                        </template>
                        <div class="share-content">
                        <img v-if="qrcodeUrls[job.id]" :src="qrcodeUrls[job.id]" class="qrcode-img" alt="分享二维码" />
                        <div class="share-link">
                            <el-input v-model="shareLinks[job.id]" size="small" readonly>
                            <template #append>
                                <el-button @click="copyLink(job.id)">复制</el-button>
                            </template>
                            </el-input>
                        </div>
                        <div class="share-tip">扫描二维码分享</div>
                        </div>
                    </el-popover>
                </div>
                </div>
            </li>
        </ul>
        <PaginationView
            :total="queryData.total"
            :pageSize="queryData.pageSize"
            :currentPage="queryData.currentPage"
            :allChoose="isAllChooseBtn"
            :pageChoose="isPageChooseBtn"
            :options="batchOptions"
            :checkedNum="checkedNum"
            :canChoose="false"
            @changeSize="handleSizeChange"
            @currentChange="handleCurrentChange"
            @changePageChoose="handlePageChoose"
            @changeAllChoose="handleAllChoose"
            @invertChoose="handleInvertChoose"
            @checkOption="handleBatchOptions"
            @refreshList="getTableData"
            @cancelChoose="handleResetPagination"
        />
    </div>
</template>

<script setup>
import { ref, onMounted,reactive } from 'vue'
import { Share,School, Collection, Timer, User, Location,StarFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { deletePostCollect,selectPostCollect } from '@/api/position'
import { tableList as mixTable } from '@ruifox-cms/utils'
import QRCode from 'qrcode'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
const router = useRouter()
//分页器
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  // isAllSearch,
  getTableData,
    handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  // handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: selectPostCollect,
});
const defaultForm = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})
Object.assign(queryData, defaultForm);

//获取收藏职位
// const loading = ref(false);
// const getJobs = async () => {
//   loading.value = true;
//   try {
//     const res = await selectPostCollect(queryData);
//     if (res.code === 20000) {
//       queryData.total = res.data.total;
//       tableData.value = res.data.list;
//     }
//   } catch (error) {
//     console.error('获取收藏职位数据失败:', error);
//   } finally {
//     loading.value = false;
//   }
// }
// 筛选配置
const filterGroups = ref([
  {
    id: 'degree',
    title: '学历要求',
    multiple: false, // 单选模式
    options: [
      { value: '', label: '不限' },
      { value: '1', label: '初中及以下' },
      { value: '2', label: '中专/中技' },
      { value: '3', label: '高中' },
      { value: '4', label: '大专' },
      { value: '5', label: '本科' },
      { value: '6', label: '硕士' },
      { value: '7', label: '博士' }
    ]
  },
  {
    id: 'workExperience',
    title: '工作经验',
    multiple: true, // 单选模式
    options: [
      { value: '', label: '不限' },
      { value: '1', label: '应届生' },
      { value: '2', label: '1-3年' },
      { value: '3', label: '3-5年' },
      { value: '4', label: '5年以上' }
    ]
  }
]);

// 获取学历标签
const getDegreeLabel = (degreeValue) => {
  const degreeGroup = filterGroups.value.find(g => g.id === 'degree');
  if (!degreeGroup) return degreeValue;
  
  const option = degreeGroup.options.find(o => o.value === degreeValue);
  return option ? option.label : degreeValue;
};

// 获取经验标签
const getExperienceLabel = (experienceValue) => {
  const expGroup = filterGroups.value.find(g => g.id === 'workExperience');
  if (!expGroup) return experienceValue;
  
  const option = expGroup.options.find(o => o.value === experienceValue);
  return option ? option.label : experienceValue;
};

//收藏职位
const toggleFavorite = async (job) => {
  try {
    // 调用取消收藏接口
    await deletePostCollect({ postId: job.id });
    // 操作成功后重新获取数据
    await handleSearch();
    
  } catch (error) {
    console.error('收藏操作失败:', error);
  }
};
onMounted(() => {
    getTableData()
})
const handleJobClick = jobId => {
  router.push(`/recruitment/user/apply?jobId=${jobId}`)
}
const qrcodeUrls = ref({})
const shareLinks = ref({})

const generateQRCode = async jobId => {
  const link = `${window.location.origin}${process.env.BASE_URL}recruitment/user/apply?jobId=${jobId}&groupId=${localStorage.getItem('recruitment-groupId')}`
  shareLinks.value[jobId] = link

  if (!qrcodeUrls.value[jobId]) {
    try {
      const url = await QRCode.toDataURL(link, {
        width: 120, // 减小二维码尺寸
        margin: 0,
        color: {
          dark: '#000',
          light: '#fff'
        }
      })
      qrcodeUrls.value[jobId] = url
    } catch (err) {
      console.error(err)
    }
  }
}

const copyLink = async jobId => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(shareLinks.value[jobId])
    } else {
      const textArea = document.createElement('textarea')
      textArea.value = shareLinks.value[jobId]
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.remove()
    }
    ElMessage.success('链接已复制')
  } catch (err) {
    console.error(err)
    ElMessage.error('复制失败')
  }
}

</script>

<style lang="scss" scoped>
.favorite-jobs-page {
    border-radius: px2rem(10);
    box-shadow: 0 0 10px rgba(#000,0.1);
    padding: px2rem(40);
    box-sizing: border-box;
    .top-section {
        display: flex;
        align-items:center;
        justify-content: space-between;
        .num {
            font-size: px2rem(16);
            span {
                color: var(--el-color-primary); 
                font-weight: bold;
            }
        }
    }
    h1 {
        color: var(--el-color-primary); 
    }
    .job-list {
        margin-top: px2rem(40);
        padding: 0;
        li {
        display: flex;
        flex-direction: column;
        border: 1px solid #eee;
        border-radius: 8px;
        padding: px2rem(20);
        box-sizing: border-box;
        margin-bottom: px2rem(20);
        transition: all 0.3s;
        &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        .top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .tit {
                font-size: px2rem(18);
                color: var(--el-color-primary);
            }
            .period {
                font-size: px2rem(16);
                flex-shrink: 0;
            }
        }
        .requirements {
            margin-top: px2rem(20);
            display: flex;
            align-items: center;
            font-size: px2rem(14);
            line-height: 1;
            color: #666;
            flex-wrap:wrap;
            gap: px2rem(5);
            .requirement-item {
                display: flex;
                align-items: center;
                
            }
        }
        .bottom {
            margin-top: px2rem(20);
            display: flex;
            justify-content: space-between;
            align-items: center;
            .job-tags {
            display: flex;
            flex-wrap:wrap;
            gap:px2rem(10);
            }
            .btns {
                flex-shrink: 0;
            }
        }
        }
    }
}
.share-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    padding: 8px;
    box-sizing: border-box;
    .qrcode-img {
        width: 120px; // 减小二维码尺寸
        height: 120px;
        display: block;
    }

    .share-link {
        width: 100%;
    }

    .share-tip {
        color: #909399;
        font-size: 12px;
    }
}
@media (max-width:960px) {
    .favorite-jobs-page {
        padding: 0;
        box-shadow: none;
        .job-list {
            margin-top: 20px;
            li {
                .top {
                    flex-wrap: wrap;
                    gap: 10px;
                }
                .bottom {
                    flex-wrap: wrap;
                    gap: 10px;
                    .el-button+.el-button {
                        margin-left: 5px;
                    }
                }
            }
        }
    }
}
</style>